package com.sky.gateway.filters;

import com.sky.common.constant.JwtClaimsConstant;
import com.sky.common.exception.LoginFailedException;
import com.sky.common.utils.JwtUtil;
import com.sky.gateway.properties.AuthProperties;
import com.sky.gateway.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author toki
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class UserAuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private final JwtProperties jwtProperties;


    /**
     * 登录校验,从请求头中获取前端传来的token，解析和校验token，不通过则拦截
     * 通过后将解析出来的信息设置到请求头（user-info）中，继续执行下一个filter
     * @param exchange 请求，包含请求信息和响应信息
     * @param chain 过滤链，包含多个filter
     * */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 登录校验
        final ServerHttpRequest request = exchange.getRequest();
        // 判断是否需要做登录拦截
        if (isExclude(request.getPath().toString())) {
            return chain.filter(exchange);
        }

//        log.info("User请求路径: {}", request.getPath());
//        log.info("请求头：{}", request.getHeaders());

        String token = null;
        final List<String> headers = request.getHeaders().get("authentication");

        if (headers != null && !headers.isEmpty()) {
            token = headers.get(0);
        }
        // 解析和校验token
        Long userId = null;
        try {
            final Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
        } catch (LoginFailedException e) {
            // 拦截，设置状态码设置为401，并返回
            final ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 结束请求
            return response.setComplete();
        }

        // 校验通过，设置用户信息到上下文
        final String userInfo = Long.toString(userId);
        // 返回新的exchange
        final ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();

        // 继续执行下一个filter,并将用户信息上下文传递过去
        return chain.filter(swe);
    }

    private boolean isExclude(String path) {
        // 获取所有放行路径,遍历，匹配
        for (String excludePath : authProperties.getUserExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }

    private boolean isInclude(String path) {
        // 获取所有需拦截判断的路径,遍历，匹配
        for (String includePath : authProperties.getUserIncludePaths()) {
            if (antPathMatcher.match(includePath, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        // 优先级比admin Filter低
        return 1;
    }
}
